<template>
    <list-layout>
        <div slot="search">
            <el-form :model="queryParams" :inline="true" ref="queryForm" v-show="showSearch" label-width="88px">
                <el-row>
                    <el-col :span="6">
                        <!--            厂区：-->
                        <el-form-item :label="$t('basicData.factoryName')" prop="factoryName">
                            <el-input v-model="queryParams.factoryName" :placeholder="$t('public.placeholder',{placeholder: $t('basicData.factoryName')})" clearable size="small" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <!--            物料编号：-->
                        <el-form-item :label="$t('basicData.materialNo')" prop="materialCode">
                            <el-input v-model="queryParams.materialCode" :placeholder="$t('public.placeholder',{placeholder: $t('basicData.materialNo')})" clearable size="small" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <!--            物料名称：-->
                        <el-form-item :label="$t('basicData.materialName')" prop="materialName">
                            <el-input v-model="queryParams.materialName" :placeholder="$t('public.placeholder',{placeholder: $t('basicData.materialName')})" clearable size="small" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
 
                </el-row>
               

                <el-row>
                    <el-col align="center">

                        <el-form-item class="right-btns">
                            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{$t('public.query')}}</el-button>
                            <el-button icon="el-icon-refresh" class="resectBtn" size="mini" @click="resetQuery">{{$t('public.reset')}}</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

        </div>
        <div class="app-container">
            <div class="container-header">
                <div class="header-left">
                    {{$t('basicData.materialInfoManagement')}}
                </div>
            </div>
            <el-row class="table-action-wrap btnGroup">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd()">{{$t('public.add')}}</el-button>
                <el-button class="exportitemBtn" size="mini"  @click="handleExport"><img src="@/assets/images/icons/daochu.png" alt=""> {{$t('public.export')}}</el-button>
                
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleSelectAdd('设置等级分类')" v-hasPermi="['qcmasterdata:material:updateInfoBatch']">设置等级分类</el-button>
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleSelectAdd('设置材料类型')" v-hasPermi="['qcmasterdata:material:updateInfoBatch']">设置材料类型</el-button>
            </el-row>
            <div class="container-table">
                <el-table :height="tableHeight" border stripe v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">

                    <el-table-column type="selection" width="55" align="center" />
                    <!--          序号-->
                    <el-table-column :label="$t('public.serialNum')" type="index" width="55" align="center" />
                    <!--          物料编号-->
                    <el-table-column :label="$t('basicData.materialNo')" align="left" prop="materialCode" minWidth="160" show-overflow-tooltip />
                    <!--          物料名称-->
                    <el-table-column :label="$t('basicData.materialName')" align="left" prop="materialName" minWidth="280" show-overflow-tooltip />
                    <!--          物料类型-->
                    <el-table-column :label="$t('basicData.materialType')" align="left" prop="materialType" minWidth="160" show-overflow-tooltip />
                    <!-- 等级分类 -->
                    <el-table-column label="等级分类"   align="left" width="100">
                        <template slot-scope="scope">
                            <div class="action-wrap">
                                {{formatQC_MASTERDATA__MATERIAL_LEVEL(scope.row.materialLevel)}}
                            </div>
                        </template>
                    </el-table-column>
                    <!-- 材料类型 -->
                    <el-table-column label="材料类型"   align="left" width="100">
                        <template slot-scope="scope">
                            <div class="action-wrap">
                                {{ formatQC_MASTERDATA__MATERIAL_KIND(scope.row.materialKind) }}
                            </div>
                        </template>
                    </el-table-column>
                    <!--          厂区-->
                    <el-table-column :label="$t('basicData.factoryName')" align="left" prop="plantName" minWidth="200" show-overflow-tooltip />
                    <!--          库位-->
                    <!-- <el-table-column label="库位" align="left" prop="locationName" minWidth="160" show-overflow-tooltip /> -->
                    <!--          标准检验时长-->
                    <el-table-column :label="$t('basicData.StandardInspectionDuration')" align="left" prop="inspectionDuration" minWidth="160" show-overflow-tooltip />
                    <!--          描述-->
                    <el-table-column :label="$t('basicData.description')" align="left" prop="description" minWidth="160" show-overflow-tooltip />
                    <!--          描述-->
                    <el-table-column :label="$t('basicData.createTime')" align="left" prop="createTime" minWidth="160" show-overflow-tooltip />
                    <el-table-column :label="$t('public.opera')" fixed="right" align="center" width="100">
                        <template slot-scope="scope">
                            <div class="action-wrap">
                                <table-body-btn type="gwedit" :name="$t('public.edit')"   @click.native="handleEdit(scope.row)" />
                                <table-body-btn type="gwdelete" :name="$t('public.delete')"  @click.native="handleDelete(scope.row)" />
                                <!-- <table-body-btn type="gwviewFiles" name="文件预览" @click.native="handlePreview(scope)" /> -->
                            </div>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" layout="total, sizes, prev, pager, next, jumper" />
            </div>

            <!-- 新增|编辑｜查看 弹框 -->
            <detail v-if="visible" :visible.sync="visible" v-model="form" :type="dialogType" @refresh="getList()"></detail>

            <batch :visible.sync="batchVisible" v-model="form" :type="dialogType" @refresh="getList()"></batch>

            <el-dialog :visible.sync="showSelect" :title="headerTitle" @close="handleClose" center top="14vh" width="500px" append-to-body :fullscreen="fullscreen">
                <el-form :model="dialogForm" size="small"   label-suffix=":" ref="detailForm"   label-width="100px">
            
                    <!--              材料类型-->
                    <el-form-item ref="materialType" label="材料类型" prop="materialKind" v-if="headerTitle=='设置材料类型'">
                        <el-select v-model="materialKind" style="width:100%"   filterable 
                        size="small" reserve-keyword :placeholder="$t('public.inputPl')+$t('basicData.materialType')">
                            <el-option v-for="(item,index) in dict.type.QC_MASTERDATA__MATERIAL_KIND" :key="index" :label="item.label" 
                            :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                
                    <!--       物料等级-->
                    <el-form-item ref="materialType" label="物料等级" prop="materialKind" v-if="headerTitle=='设置等级分类'">
                        <el-select v-model="materialLevel" style="width:100%"   filterable size="small" reserve-keyword :placeholder="$t('public.inputPl')+$t('basicData.materialType')">
                            <el-option v-for="(item,index) in dict.type.QC_MASTERDATA__MATERIAL_LEVEL" :key="index" :label="item.label" :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                   

                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="submitForm" :loading="loading" icon="el-icon-document" size="small">{{$t('public.save')}}</el-button>
                </div>
            </el-dialog>
        </div>
    </list-layout>
</template>

<script>
import {mapState} from 'vuex'
import {refreshCache} from '@/api/basic/dict/type'
import {geFileByBiz} from '@/api/file/file'
import base from '@/utils/base64' //引入
import {delMaterialMessage, getMaterialFile, listMaterialMessage,updateInfoBatchAPI} from '@/api/basic/materialMessage'
import {getMasterialMaxMinData,} from '@/api/basic/materialtype'
import Detail from './detial.vue'
import Batch from './batch.vue'
//基础数据-物料信息管理
export default {
    name: 'materialinfo',
    dicts: ['QC_MASTERDATA__MATERIAL_KIND','QC_MASTERDATA__MATERIAL_LEVEL'],
    components: { Detail, Batch },
    computed: {
        ...mapState({
            isFold: (state) => state.app.isFold,
        }),
    },
    watch: {
        isFold(val) {
            if (val === true) {
                this.tableHeight = 'calc(100vh - 308px)'
            } else {
                this.tableHeight = 'calc(100vh - 396px)'
            }
        },
    },
    data() {
        return {
            dialogType: 1, //1:新增  2：编辑 3：查看
            dialogForm: {},
            tableHeight: 'calc(100vh - 308px)',
            materialMaxOptions: [],
            materialMiddleOptions: [],
            direction: 'rtl',
            addInspection: false,
            visible: false,
            batchVisible: false,
            drawer: false,
            approvalOpen: false,
            viewModel: {
                inspectionInformation: '0',
            },
            editModel: {
                inspectionInformation: '0',
            },
            approvalForm: {
                status: '1',
                textarea: '',
            },
            selBtn: 1,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 字典表格数据
            typeList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 日期范围
            dateRange: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 20,
                factoryName: '',
                materialType: '',
                materialCode: '',
                materialName: '',
                materialMax: [],
                materialMiddle: [],
                maturity: [],
            },
            // 表单参数
            form: undefined,
            materialOptions: [],
            fullscreen: false,
            names: [],
            showSelect:false,
            headerTitle:"设置材料类型",
            materialOptions: [
                {value:"1",label:"主材"},
                {value:"2",label:"辅材"}
            ],
            materialLevel:"",
            materialKind:""
        }
    },
    created() {
        this.getList()
        // this.getMaterialType({}, 'materialMax')
        // this.getMaterialType({ materialMax: 'all' }, 'materialMiddle')
        // this.getMaterialType({ materialMiddle: 'all' }, 'typeName')
    },
    methods: {
        formatQC_MASTERDATA__MATERIAL_LEVEL(e){
            try{
                let obj = this.dict.type.QC_MASTERDATA__MATERIAL_LEVEL.find((item) => {
                    return item.value === e
                })
                return obj.label
            }catch(e){
                return ''
            }
        },
        formatQC_MASTERDATA__MATERIAL_KIND(e){
            try{
                let obj = this.dict.type.QC_MASTERDATA__MATERIAL_KIND.find((item) => {
                    return item.value === e
                })
                return obj.label
            }catch(e){
                return ''
            }
        },
        handleSelectAdd(headerTitle){
            if(this.ids.length==0){
                this.$modal.msgWarning('请先选择物料！')
                return
            }
            this.headerTitle=headerTitle
            this.showSelect=true
        },
        handleClose(){
            this.materialLevel=''
            this.materialKind=''
            this.showSelect=false
        },
        submitForm(){
            var data={
                infoType:this.headerTitle=='设置等级分类' ? '1':'0',
                infoValue:this.headerTitle=='设置等级分类' ? this.materialLevel:this.materialKind,
                materialIds:this.ids
            }
            if(data.infoValue===''){
                this.$modal.msgWarning('请'+this.headerTitle)
                return
            }
            updateInfoBatchAPI(data).then(res=>{

                this.handleClose()
                this.getList()
            })
        },
        filterParams(p) {
            if (p && p.length) {
                return p.join(',')
            } else {
                return ''
            }
        },
        drawerClose() {
            this.drawer = false
        },
        getMaterialType(params, name) {
            let array = []
            getMasterialMaxMinData(params).then((res) => {
                array = res.data.map((item) => item[name])
                if (name === 'materialMax') {
                    this.materialMaxOptions = array
                } else if (name === 'materialMiddle') {
                    this.materialMiddleOptions = array
                } else {
                    this.materialOptions = array
                }
            })
        },
        /** 查询字典类型列表 */
        getList() {
            this.loading = true
            let params = JSON.parse(JSON.stringify(this.queryParams))
            params.materialMax = this.filterParams(params.materialMax)
            params.materialMiddle = this.filterParams(params.materialMiddle)
            params.maturity = this.filterParams(params.maturity)
            console.log(params)
            listMaterialMessage(params).then((response) => {
                if (response.code == 200 && response.rows) {
                    this.typeList = response.rows
                    this.total = response.total
                    this.loading = false
                }
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                dictId: undefined,
                dictName: undefined,
                dictType: undefined,
                status: '0',
                remark: undefined,
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = []
            this.resetForm('queryForm')
            this.handleQuery()
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.form = {}
            this.dialogType = 1
            this.visible = true
        },
        handleRemove() {
            if (this.ids.length === 0) {
                this.$modal.msgWarning(
                    this.$t('inspectionManagement.pleaseSelectOne')
                )
                return
            }
            this.handleDelete()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.materialId)
            this.names = selection.map((item) => item.materialName)
            // this.single = selection.length!=1
            // this.multiple = !selection.length
        },
        handleMaterialMaxChange(e) {
            this.getMaterialType(
                { materialMax: e.join(',') || 'all' },
                'materialMiddle'
            )
            if (this.queryParams.materialMiddle.length) {
                this.$set(this.queryParams, 'materialMiddle', [])
            }
            if (this.queryParams.materialType) {
                this.$set(this.queryParams, 'materialType', '')
            }
        },
        handleMaterialMiddleChange(e) {
            this.getMaterialType(
                { materialMiddle: e.join(',') || 'all' },
                'typeName'
            )
            if (this.queryParams.materialType) {
                this.$set(this.queryParams, 'materialType', '')
            }
        },
        handleMaturityChange(e) {
            console.log(e)
            this.queryParams.maturity = e.join(',')
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            // const dictIds = (row && row.id) || this.ids
            // const names = (row && row.materialName) || this.names
            this.$modal
                .confirm('是否确认删除物料名称为"' + row.materialName + '"的数据项？')
                .then(function () {
                    return delMaterialMessage(row.materialId)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess(this.$t('processDefinition.successfullyDeleted'))
                })
                .catch(() => {})
        },
        /** 查看按钮操作 */
        handleView(row) {
            this.dialogType = 3
            this.form = row
            this.visible = true
            // if(row.hasRead == 0){
            //   readNotice(row.noticeId).then(res=>{
            //     if(res.code == 200){
            //       this.handleQuery()
            //     }
            //   })
            // }
        },
        handlePreview(scope) {
            getMaterialFile({ materialCode: scope.row.materialCode }).then(
                (res) => {
                    if (res.data && res.data.id) {
                        let base64 = new base()
                        geFileByBiz({ bizId: res.data.id }).then((response) => {
                            if (response.data.length > 0) {
                                window.open(
                                    'http://kkfile-view.asensing.com/onlinePreview?url=' +
                                        encodeURIComponent(
                                            base64.encode(response.data[0].url)
                                        )
                                )
                            } else {
                                this.$modal.msgWarning('没有找到文件!')
                            }

                            // console.log('otherList=========', this.otherList)
                        })
                    }
                }
            )
        },
        /** 编辑按钮操作 */
        handleEdit(row) {
            this.dialogType = 2
            this.form = row
            this.visible = true
        },
        
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                'masterdata/material/export',
                {
                    ...this.queryParams,
                },
                `materialMessage_${new Date().getTime()}.xlsx`
            )
        },
        /** 刷新缓存按钮操作 */
        handleRefreshCache() {
            refreshCache().then(() => {
                this.$modal.msgSuccess('刷新成功')
            })
        },
        handleMod() {
            this.dialogType = 2
            this.batchVisible = true
        },
    },
}
</script>
<style lang="scss" scoped>
::v-deep .el-card {
    padding-top: 20px;
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 4px;
    padding-bottom: 20px;
}
::v-deep .el-aside {
    padding: 0;
    margin-bottom: 0;
}
.content-style {
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 2px;
    background-color: white;
    margin-top: 10px;
}
::v-deep .el-button-group .selBtn {
    background: #fff;
    border: 1px solid #0b7be3;
    color: #0b7be3;
}
::v-deep .el-button-group .unselBtn {
    background: #fff;
    border: 1px solid #ededf2;
    color: #666666;
}
.header-left {
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #333333;
    padding: 3px 0 10px;
    display: inline-flex;
    justify-content: center;
    border-bottom: 2px solid #0b7be3;
}
.header-right {
    float: right;
}
.container-header {
    border-bottom: 1px solid #ededf2;
}
.container-table {
    float: left;
    //margin-top:6px;
    width: 100%;
}
.mb8 {
    float: left;
    margin-top: 6px;
    width: 100%;
}
.drawer-footer {
    display: flex;
    position: relative;
    z-index: 9999;
    bottom: -40px;
    height: 40px;
    justify-content: center;
    width: 100%;
}
.drawer-close {
    background: #f7f8fa;
    border-color: #f7f8fa;
}

.right-btns ::v-deep .el-button {
    margin-top: 0;
}
.app-container {
    padding: 0;
}
.table-action-wrap {
    padding: 12px 0;
}
</style>
